import csv
import states
import requests

from bs4 import BeautifulSoup


def request(method, params):
	params['key'] = 'x'
	r = requests.get('http://api.votesmart.org/' + method, params=params)
	print r.url
	return BeautifulSoup(r.text, 'xml')


def getSigLatestRating(sig_id):
	# LCV
	if sig_id == '1012':
		return {'ratingId': 9488, 'timespan': '2015?', 'sigId': sig_id}
	# NRA
	if sig_id == '1034':
		return {'ratingId': 10178, 'timespan': '2015?', 'sigId': sig_id}
	# NFIB
	if sig_id == '933':
		return {'ratingId': 10133, 'timespan': '2015-16', 'sigId': sig_id}

	latest_rating = request('Rating.getSigRatings', {'sigId': sig_id}).find_all('rating')[0]
	return {'ratingId': latest_rating.ratingId.text, 'timespan': latest_rating.timespan.text, 'sigId': sig_id}


### INTEREST GROUP RATINGS
def getRatings(sig_id):
	latest_rating = getSigLatestRating(sig_id)
	assert latest_rating['sigId'] == sig_id
	ratings = []
	soup = request('Rating.getRating', {'ratingId': latest_rating['ratingId']})
	for rating in soup.find_all('candidateRating'):
		ratings.append({'sig_id': sig_id,
			'ratingId': latest_rating['ratingId'],
			'candidateId': rating.candidateId.text,
			'rating': rating.rating.text})
	return ratings


interest_group_ids = []
with open('vote_and_group_info_map.csv', 'rbU') as csvfile:
	r = csv.DictReader(csvfile, delimiter=',')
	for row in r:
		interest_group_ids.append(row['sig_id'])


with open('sig_ratings.csv', 'w') as csv_file:
	writer = csv.DictWriter(csv_file, ['sig_id', 'candidateId', 'rating'], extrasaction='ignore')
	writer.writeheader()
	for sig_id in interest_group_ids:
		print 'Now on sig %s' % sig_id
		for sig_rating in getRatings(sig_id):
			try:
				writer.writerow(sig_rating)
			except:
				print 'Failed on rating %s' % sig_rating